<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use Telegram\Bot\Api;

class CronTab extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'CronTab';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时推送消息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $cron = DB::table("tg_crontab")->where("status",1)->get();
        foreach ($cron as $Key){
            if( time() - strtotime($Key->updated_at) >= $Key->count_down){
                
                $group = DB::table("tg_group")->where("id",$Key->group_id)->first();
                $bot = DB::table("tg_bot")->where("id",$group->bot_id)->first();
                $keyword = DB::table("tg_keyword")->where("id",$Key->key_id)->first();
                
                $telegram = new Api($bot->bot_token);
                $response = $telegram->sendMessage([
                  'chat_id' => $group->chat_id,
                  'text' => $keyword->content
                ]);

                if($response){
                    $res = DB::table("tg_crontab")->where("id",$Key->id)->update(['updated_at'=>date("Y-m-d H:i:s")]);
                }
                
            }
        }
    }
    
   
}
